# -*- coding: utf-8 -*-
import sys
from io import TextIOWrapper
from time import time
from concurrent.futures import wait
from video_compressor import printf
from video_compressor import Colors
from video_compressor import THREAD_POOL
from video_compressor import compressor
from video_compressor import splicing
from video_compressor import slice
from video_compressor import splicing_xfade


# 设置标准输出编码为UTF-8
sys.stdout = TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
sys.stderr = TextIOWrapper(sys.stderr.buffer, encoding='utf-8')


def exit_close(tasks=[]):
    printf(f'{Colors.OKGREEN}运行结束 任务数量: {Colors.ENDC}{Colors.OKBLUE}{len(tasks)}{Colors.ENDC} {Colors.OKGREEN}耗时:{time() - start_time}{Colors.ENDC}')
    THREAD_POOL.shutdown(wait=True)
    input("按回车键退出...")
    sys.exit(0)


func_dict = {0: exit_close, 1: compressor.get_tasks, 2: slice.get_tasks,
             3: splicing.get_tasks, 4: splicing_xfade.get_tasks}
choice_set = set(map(lambda x: str(x), func_dict.keys()))


def get_user_input():
    sys.stdout.write("\033[2J\033[H")
    printf(f"{Colors.OKBLUE}请选择操作:{Colors.ENDC}")
    printf(f"{Colors.OKBLUE}0. 退出{Colors.ENDC}")
    printf(f"{Colors.OKBLUE}1. 视频压缩{Colors.ENDC}")
    printf(f"{Colors.OKBLUE}2. 视频切片{Colors.ENDC}")
    printf(f"{Colors.OKBLUE}3. 视频合并{Colors.ENDC}")
    printf(f"{Colors.OKBLUE}4. 剧集前情摘要{Colors.ENDC}")

    while True:
        sys.stdout.write(f"\033[7;1H\033[2K\r")
        choice = input(f"{Colors.OKBLUE}请输入选项 {Colors.ENDC}(0-3): \n")
        if choice in choice_set:
            return int(choice)
        printf(f"{Colors.WARNING}无效输入，请重新选择{Colors.ENDC}")


if __name__ == '__main__':
    choice = get_user_input()
    func = func_dict.get(choice)
    start_time = time()
    tasks = func()
    if not tasks: printf(f'{Colors.WARNING}没有可执行的任务{Colors.ENDC}')
    else: wait(tasks)
    exit_close(tasks=tasks)


